package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.dto.pojo.*;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.SpuMapper;
import com.leyou.item.pojo.Sku;
import com.leyou.item.pojo.Spu;
import com.leyou.item.pojo.SpuDetail;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.leyou.common.constants.MQConstants.Exchange.*;
import static com.leyou.common.constants.MQConstants.RoutingKey.*;

/**
 * @author HeGuanChao
 * @Description TODO
 * @Date 2020/4/2 17:23
 */
@Service
public class GoodsService {
    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SpuDetailMapper spuDetailMapper;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private AmqpTemplate amqpTemplate;


    public PageResult<SpuDTO> querySpuByPage(String key, Boolean saleable,
                                             Integer page, Integer rows) {
        // 设置分页
        PageHelper.startPage(page, rows);
        // 条件查询
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        // 排除空格参数
        if (StringUtils.isNotBlank(key)) {
            // 模糊查询条件 like
            criteria.andLike("name", "%" + key + "%");
        }
        // 是否上下架
        if (saleable != null) {
            criteria.andEqualTo("saleable", saleable);
        }

        // 排序
        example.setOrderByClause("update_time DESC");
        // 查询结果
        List<Spu> spuList = spuMapper.selectByExample(example);
        // 判空
        if (CollectionUtils.isEmpty(spuList)) {
            // 商品不存在
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        // 封装结果
        PageInfo<Spu> pageInfo = new PageInfo<>(spuList);

        // 转换为dto
        List<SpuDTO> spuDTOList = BeanHelper.copyWithCollection(spuList, SpuDTO.class);
        // 处理分类和品牌的名称
        handleCategoryAndBrandName(spuDTOList);

        return new PageResult<>(pageInfo.getTotal(), spuDTOList);
    }

    /**
     * 处理分类和品牌的名称
     *
     * @param spuDTOList
     */
    private void handleCategoryAndBrandName(List<SpuDTO> spuDTOList) {
        for (SpuDTO spuDTO : spuDTOList) {
            // 查询分类名称
            List<Long> categoryIds = spuDTO.getCategoryIds();
            String name = categoryService.queryByIds(categoryIds)
                    .stream()
                    .map(CategoryDTO::getName)
                    .collect(Collectors.joining("/"));
            spuDTO.setCategoryName(name);
            // 查询品牌名称
            Long brandId = spuDTO.getBrandId();
            BrandDTO brandDTO = brandService.queryById(brandId);
            spuDTO.setBrandName(brandDTO.getName());
        }
    }

    /**
     * 新增商品
     *
     * @param spuDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveGoods(SpuDTO spuDTO) {
        // 将dto转为实体类
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        // 商品修改必须先下架
        spu.setSaleable(false);
        // 保存信息
        int count = spuMapper.insertSelective(spu);

        if (count != 1) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
        // 保存spuDetail
        SpuDetailDTO spuDetailDTO = spuDTO.getSpuDetail();
        SpuDetail spuDetail = BeanHelper.copyProperties(spuDetailDTO, SpuDetail.class);
        spuDetail.setSpuId(spu.getId());
        count = spuDetailMapper.insertSelective(spuDetail);
        if (count != 1) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        // 保存sku集合
        List<SkuDTO> skuDTOS = spuDTO.getSkus();
        List<Sku> skus = BeanHelper.copyWithCollection(skuDTOS, Sku.class);
        skus.forEach(sku -> {
            sku.setSpuId(spu.getId());
        });
        count = skuMapper.insertList(skus);
        if (count != skus.size()) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    /**
     * 修改商品的上下架
     *
     * @param id
     * @param saleable
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateSaleable(Long id, Boolean saleable) {
        // 封装条件
        Spu spu = new Spu();
        spu.setId(id);
        spu.setSaleable(saleable);
        int count = spuMapper.updateByPrimaryKeySelective(spu);
        if (count != 1) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        // 更新sku
        Sku sku = new Sku();
        sku.setEnable(saleable);
        // 条件
        Example example = new Example(Sku.class);
        example.createCriteria().andEqualTo("spuId", id);
        count = skuMapper.updateByExampleSelective(sku, example);
        if (count < 1) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        // 上下架的操作，把上下架消息发送到队列中：静态化服务和搜索微服务消费
        amqpTemplate.convertAndSend(ITEM_EXCHANGE_NAME, (saleable ? ITEM_UP_KEY : ITEM_DOWN_KEY), id);
    }

    /**
     * 根据id查询商品信息
     *
     * @param id
     * @return
     */
    public SpuDetailDTO querySpuDetailSpuId(Long id) {
        SpuDetail spuDetail = spuDetailMapper.selectByPrimaryKey(id);
        if (spuDetail == null) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyProperties(spuDetail, SpuDetailDTO.class);
    }

    /**
     * 根据id查询sku列表
     *
     * @param id
     * @return
     */
    public List<SkuDTO> querySkuListBySpuId(Long id) {
        Sku sku = new Sku();
        sku.setSpuId(id);
        List<Sku> skuList = skuMapper.select(sku);
        if (CollectionUtils.isEmpty(skuList)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(skuList, SkuDTO.class);
    }

    /**
     * 修改商品信息
     *
     * @param spuDTO
     */
    public void updateGoods(SpuDTO spuDTO) {
        // 获取id
        Long spuId = spuDTO.getId();
        // 判断id是否为空
        if (spuId == null) {
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }

        // 删除sku
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        // 查询sku的数量
        int size = skuMapper.selectCount(sku);
        if (size > 0) {
            // 删除sku
            int count = skuMapper.delete(sku);
            if (size != count) {
                throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
            }
        }

        // 更新spu
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        spu.setSaleable(null);
        spu.setCreateTime(null);
        int count = spuMapper.updateByPrimaryKeySelective(spu);
        if (count != 1) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        // 更新SpuDetail
        SpuDetail spuDetail = BeanHelper.copyProperties(spuDTO.getSpuDetail(), SpuDetail.class);
        spuDetail.setSpuId(spuId);
        spuDetail.setCreateTime(null);
        count = spuDetailMapper.updateByPrimaryKeySelective(spuDetail);
        if (count != 1) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        // 新增sku集合（先删后增）
        List<SkuDTO> skuDTOS = spuDTO.getSkus();
        List<Sku> skus = BeanHelper.copyWithCollection(skuDTOS, Sku.class);
        skus.forEach(s -> {
            s.setSpuId(spuId);
        });
        count = skuMapper.insertList(skus);
        if (count != skus.size()) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
    }

    public SpuDTO querySpuById(Long id) {
        // 根据id查询spu商品描述表数据
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (spu == null) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        // 转换为dto实体
        SpuDTO spuDTO = BeanHelper.copyProperties(spu, SpuDTO.class);
        // 查询detail商品描述详情表 并赋值给spuDto
        spuDTO.setSpuDetail(querySpuDetailSpuId(id));
        // 查询sku商品实体表
        spuDTO.setSkus(querySkuListBySpuId(id));
        return spuDTO;
    }

    public List<SkuDTO> querySpuByIds(List<Long> ids) {
        // 查询sku
        List<Sku> skuList = skuMapper.selectByIdList(ids);
        if (CollectionUtils.isEmpty(skuList)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(skuList, SkuDTO.class);
    }

    @Transactional(rollbackFor = Exception.class)
    public void minusStock(Map<Long, Integer> cartMap) {
        // 遍历map
        for (Map.Entry<Long, Integer> entry : cartMap.entrySet()) {
            Long skuId = entry.getKey();
            Integer num = entry.getValue();
            // 修改库存量
            int count = skuMapper.minusStock(skuId, num);
            // 数据库返回的值：成功：1，失败：0
            if (count != 1) {
                throw new RuntimeException("库存不足");
            }
        }
    }
}
